package com.bpzj.util.dto.mapstruct;

import com.bpzj.util.dto.Person;
import com.bpzj.util.dto.PersonDto;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;


/*
 * Int/Float 转 String, 编译后生成的方法调用的是
 *      DecimalFormat("0.00")
 *      DecimalFormat("#.##E0")
 * numberFormat = "0.00"    保留两位小数
 *
 * idea中编译报错 解决方案：
  Setting -> Build,Execution,Deployment -> Compiler -> User-local build process VM options 加上参数：
    -Djps.track.ap.dependencies=false
 */
@Mapper
public interface PersonMapper {

  PersonMapper INSTANCE = Mappers.getMapper(PersonMapper.class);

  @Mapping(target = "age", numberFormat = "#.##E0")
  @Mapping(target = "birthday", dateFormat = "yyyy-MM-dd")
  @Mapping(target = "deadTime", expression = "java(java.time.LocalDateTime.now())")
  Person dtoToPerson(PersonDto dto);


  @Mapping(target = "age", source = "age", numberFormat = "0.00")
  @Mapping(target = "birthday", source = "birthday", dateFormat = "yyyy-MM-dd")
  @Mapping(target = "deadTime", dateFormat = "yyyy-MM-dd HH:mm:ss")
  PersonDto personToDto(Person person);


  default Person mapToPerson(Map<String, Object> map) {
    Person person = new Person();
    person.setName((String) map.get("name"));
    person.setAge((Integer) map.get("age"));
    try {
      person.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse((String) map.get("birthday")));
    } catch (ParseException e) {
      person.setBirthday(null);
    }

    return person;
  }

  // 假如 expression 是一个 api特别长 的方法, 不好复制, 可以这样做:
  // 在当前接口 创建 default 方法: 在 default 方法中调用 那个较长的api, 然后expression中直接使用 default方法
  @Mapping(target = "idCardNo", expression = "java(defaultCard())")
  @Mapping(target = "birthday", dateFormat = "yyyy-MM-dd")
  Person dtoToPersonTest(PersonDto dto);

  default String defaultCard() {
    return "defaultCardNo";
  }
}
